package com.soushangxing.comfyuibackendv2.service

import com.soushangxing.comfyuibackendv2.bean.GlobalQueue
import com.soushangxing.comfyuibackendv2.bean.ResponseType
import com.soushangxing.comfyuibackendv2.config.WebSocketManager
import com.soushangxing.comfyuibackendv2.entity.ComfyUIServerEntity
import com.soushangxing.comfyuibackendv2.repository.ServerRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class ServerService {
    @Autowired
    lateinit var serverRepository:ServerRepository

    @Autowired
    lateinit var webSocketManager: WebSocketManager

    @Autowired
    lateinit var globalQueue: GlobalQueue

    @Autowired
    lateinit var globalQueueService: GlobalQueueService


    fun addServer(url:String, taskLimit:Int,
                  name:String?, description:String?):ResponseType{
        try {
            val server = ComfyUIServerEntity()
            server.url = url
            server.taskLimit = taskLimit
            server.status = "停止"
            server.name = name
            server.description = description
            serverRepository.save(server)
            return ResponseType(server,0,"服务器添加完毕")
        } catch (e:Exception){
            return ResponseType("添加服务器出错")
        }
    }

    fun startServerByUrl(url: String): ResponseType {
        val server = serverRepository.findFirstByUrl(url)
        return if (server != null) {
            try {
                webSocketManager.connect(server.url, "client-${server.id}")

                // 等待连接建立（最多等待 10 秒）
                var attempts = 0
                while (!webSocketManager.isConnected(server.url) && attempts < 10) {
                    Thread.sleep(1000)
                    attempts++
                }

                if (webSocketManager.isConnected(server.url)) {
                    globalQueueService.checkQueue()

                    ResponseType(server, 0, "服务器启动成功")
                } else {
                    throw Exception("无法建立WebSocket连接")
                }
            } catch (e: Exception) {
                ResponseType("启动服务器出错: ${e.message}")
            }
        } else {
            ResponseType("服务器未找到")
        }
    }

    fun stopServerByUrl(url: String): ResponseType {
        val server = serverRepository.findFirstByUrl(url)
        return if (server != null) {
            try {
                webSocketManager.disconnect(server.url)
                ResponseType(server, 0, "服务器停止成功")
            } catch (e: Exception) {
                ResponseType("停止服务器出错: ${e.message}")
            }
        } else {
            ResponseType("服务器未找到")
        }
    }

    fun getServerList() :ResponseType{
        return ResponseType(serverRepository.findAll(),0,"查询完毕")
    }

    fun changeServerTaskLimitByUrl(url:String, taskLimit:Int):ResponseType{
        val server = serverRepository.findFirstByUrl(url)
        return if (server != null) {
            try {
                webSocketManager.disconnect(server.url)
                server.taskLimit = taskLimit
                serverRepository.save(server)

                // 处理全局 globalServer 数组
                val existingServerIndex = globalQueue.globalServer.indexOfFirst { it.url == server.url }
                if (existingServerIndex == -1) {
                    // 如果不存在相同 URL 的服务器，则添加新服务器
                    globalQueue.globalServer.add(server)
                } else {
                    // 如果存在相同 URL 的服务器，则更新其状态
                    globalQueue.globalServer[existingServerIndex].taskLimit = taskLimit
                }

                ResponseType(server, 0, "服务器任务数量更改成功")
            } catch (e: Exception) {
                ResponseType("服务器更改出错: ${e.message}")
            }
        } else {
            ResponseType("服务器未找到")
        }
    }

}
